﻿namespace Common.Helpers
{
    using System;
    using System.Threading.Tasks;

    using Timer = System.Timers.Timer;

    public class AsyncActionWrapper
    {
        private Task task;

        private Timer timer;

        public event EventHandler ActionComplited;

        public AsyncActionWrapper(Action action)
        {
            this.task = new Task(action);
        }

        public void Start()
        {
            this.task.Start();
            this.StartTimer();
        }
        
        private void StartTimer()
        {
            this.timer = new Timer(200);
            GC.KeepAlive(this.timer);
            this.timer.Elapsed += this.TimerElapsedEventHandler;
            this.timer.Start();
        }

        private void TimerElapsedEventHandler(object sender, EventArgs e)
        {
            if (this.task.IsCompleted && this.ActionComplited != null)
            {
                this.timer.Stop();
                this.timer.Dispose();
                this.ActionComplited(this, null);
            }
        }
    }
}